const http = require('http');
const fs = require('fs');
const port = process.env.PORT || 3000;

function serveStaticFile(res, path, contentType, responseCode) {
    fs.readFile(`${__dirname}/public${path}`, (err, data) => {
        if (err) {
            console.dir(err);
            res.writeHead(500, {'Content-Type': 'text/plain'});
            return res.end('500 - Internal Server Error');
        }
        res.writeHead(responseCode, {'Content-Type': contentType});
        res.end(data);
    });
}

http.createServer((req, res) => {
    const path = req.url.replace(/\/?(?:\?.*)?$/, '');
    switch (path) {
        case '/':
            serveStaticFile(res, '/index.html', 'text/html', 200);
            break;
        case '/about':
            serveStaticFile(res, '/about.html', 'text/html', 200);
            break;
        case '/contact':
            serveStaticFile(res, '/contact.html', 'text/html', 200);
            break;
        default:
            serveStaticFile(res, '/404.html', 'text/html', 404);
    }
}).listen(port, () => {
    console.log(`Server is running on port ${port}`);
    console.log('Press Ctrl+C to stop the server');
});

